﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using System.ComponentModel.Composition;
using System.IO;
using System.Data;
using System.Diagnostics.CodeAnalysis;

namespace Steve.EFDataLayer
{
    [Export(typeof(CategoryRepository))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class EFCategoryRepository : CategoryRepository
    {
        static EFCategoryRepository()
        {
            SteveEFDataLayer.SetupAutoMapper();
        }

        protected override IEnumerable<Category> GetCategoriesCore()
        {
            using (var ctx = new SteveEntities())
            {
                var query = from c in ctx.DbCategories
                            select c;

                return query.ToList().Select(c => Mapper.Map<DbCategory, Category>(c));
            }
        }

        protected override Category SaveCategoryCore(Category toSave)
        {
            using (var ctx = new SteveEntities())
            {
                var existing = (from c in ctx.DbCategories
                                where c.CategoryName == toSave.CategoryName
                                select c).FirstOrDefault();

                if (existing == null)
                {
                    existing = new DbCategory();
                    ctx.AddToDbCategories(existing);
                }

                Mapper.Map(toSave, existing);

                ctx.SaveChanges();

                return Mapper.Map<DbCategory, Category>(existing);
            }
        }

    }
}
